package com.shelpe.services.tenant.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.ansj.domain.Result;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.shelpe.services.tenant.dao.RptItemsViewMapper;
import com.shelpe.services.tenant.dto.CoreWordDto;
import com.shelpe.services.tenant.model.Adgroups;
import com.shelpe.services.tenant.model.Auth;
import com.shelpe.services.tenant.model.Products;
import com.shelpe.services.tenant.model.RptItemsViewExample;
import com.shelpe.services.tenant.model.Users;
import com.shelpe.services.tenant.proxy.RecommendClient.RecommendWord;
import com.shelpe.services.tenant.service.AdgroupService;
import com.shelpe.services.tenant.service.AuthService;
import com.shelpe.services.tenant.service.CoreWordService;
import com.shelpe.services.tenant.service.ProductService;
import com.shelpe.services.tenant.service.UserService;


@RestController
@RequestMapping(value="/jobserver")
public class CoreWordController {

	private static final Logger logger = LoggerFactory.getLogger(CoreWordController.class);
	
	@Autowired
	private CoreWordService coreWordService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private AdgroupService adgroupService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private AuthService authService;
	
	@Autowired
	private RptItemsViewMapper rptItemMapper;
	
	@Value("${jobserver.mainInnerUserId}")
	private String mainInnerUserId;
	
	private final ExecutorService executor = Executors.newSingleThreadExecutor();
	
	@RequestMapping("/testview")
	@ResponseBody
	public Integer testView(){
		
		RptItemsViewExample example = new RptItemsViewExample();
		
		return rptItemMapper.countByExample(example);
	}
	
	@RequestMapping("/segment")
	@ResponseBody
	public Result segment(@RequestParam(value = "word", required = false) String word){
		
		return ToAnalysis.parse(word);
	}
	
	@RequestMapping("/coreword")
	@ResponseBody
	public CoreWordDto UpdateCoreWord(@RequestParam(value = "user_id", required = false) final Long userId){
		
		CoreWordDto dto = new CoreWordDto();
		
		CompletionService<CoreWordDto> comletionService = new ExecutorCompletionService<CoreWordDto>(executor); 
		
		comletionService.submit(new Callable<CoreWordDto>(){

			@Override
			public CoreWordDto call() throws Exception {
				// TODO Auto-generated method stub
				List<Users> filterUsers = new ArrayList<Users>();
				if(userId != null){
					Users user = userService.getUserByUserId(userId);
					filterUsers.add(user);
				}else{
					List<Users> users = userService.getAllUsers();
					filterUsers = filterUser(users);
				}
				
				for(Users user : filterUsers){
					
					Long userId = user.getUserId();			
					String nick = user.getNick();
					logger.info("UpdateCoreWord userId: {}, nick: {}", userId, nick);
					List<Adgroups> ads = adgroupService.getAdgroupsByUserId(userId);
					if(ads != null && ads.size() > 0){
						for(Adgroups ad : ads){
							
							Long adgroupId = ad.getAdgroupId();
							Long numIid = ad.getNumIid();
							Products product = productService.getProductById(numIid);
							if(product != null){
								
								List<RecommendWord> reWord = coreWordService.getKeywordByRecommand(nick, adgroupId);						
								JSONArray core = coreWordService.getCoreWordFromRecommendWord(reWord);							
								String oldCore = product.getCoreWord();
								
								//logger.info(">>>>>>>>>>>numiid: {}, core: {}", numIid, core);
								if(core != null && !core.isEmpty() && !core.toJSONString().equals(oldCore)){
									product.setCoreWord(core.toJSONString());
									productService.updateItems(product);
								}
							}else{
								logger.info("UpdateCoreWord can not find item by numiid: {}", numIid);
							}
						}
					}
				}
				
				return null;
			}	
		});
		
		dto.setMessage("success");
		
		return dto;
	}
	
	private List<Users> filterUser(List<Users> list){
		
		List<Long> innerUserIdList = new ArrayList<Long>();
		if(mainInnerUserId != null){
			
			String[] innerUserId = mainInnerUserId.split(",");

			if(innerUserId != null && innerUserId.length > 0){
				for(int i = 0; i < innerUserId.length; i++){
					innerUserIdList.add(Long.valueOf(innerUserId[i]));
				}
			}
		}

		List<Users> temp = new ArrayList<Users>();
		if(list != null && list.size() > 0){
			
			for(Users user : list){
				Long userId = user.getUserId();
				Long authorizedTo = user.getAuthorizedTo();
				
				if(userId > 0 || innerUserIdList.contains(authorizedTo)){
					temp.add(user);
				}else{
					List<Auth> authList = authService.getAuthByUserId(userId);
					if(authList != null && authList.size() > 0){
						temp.add(user);
					}
				}
			}
		}
		return temp;
	}
	
}
